package org.goldfish.message_board01.servlets;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.goldfish.message_board01.services.UserService;

import java.io.IOException;
import java.util.List;

import static org.goldfish.message_board01.filters.CustomAuthFilter.ONLINE_USERS;


public class LoginServlet extends GFAbstractServlet {
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username, password;
        try {
            username = request.getAttribute("username").toString();
            password = request.getAttribute("password").toString();
        } catch (NullPointerException e) {
            doGet(request, response);
            return;
        }
        String rememberMe = request.getParameter("rememberMe");

        boolean isValidUser = userService.validateUser(username, password); // 验证用户名和密码
        if (isValidUser) {
            // 保存用户信息到 Session
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            String encryptedUsername = userService.cesarEncrypt(username);
            String encryptedPassword = userService.cesarEncrypt(password);
            System.out.println("writing to cookie: " + encryptedUsername + " " + encryptedPassword);

            // 处理 "记住我" 功能
            if ("on".equals(rememberMe)) {
                System.out.println("remember me");
                // 创建两个 Cookie
                Cookie usernameCookie = new Cookie("username", encryptedUsername);
                Cookie passwordCookie = new Cookie("password", encryptedPassword);

                // 设置 Cookie 的有效期为 7 天
                usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                passwordCookie.setMaxAge(60 * 60 * 24 * 7);

                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            } else {
                System.out.println("not remember me");
                // 清除之前的 Cookie
                Cookie usernameCookie = new Cookie("username", userService.cesarEncrypt(username));
                Cookie passwordCookie = new Cookie("password", userService.cesarEncrypt(password));

                usernameCookie.setMaxAge(0);
                passwordCookie.setMaxAge(0);

                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }
            try {
                request.getSession().setAttribute("username", username);
                Object obj = request.getServletContext().getAttribute(ONLINE_USERS);
                if (obj instanceof List) {
                    List<String> onlineUsers = (List<String>) obj;
                    onlineUsers.add(username);
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }

            request.getSession().setAttribute("username", username);
            // 跳转到消息列表页面
            response.sendRedirect("messages");
        } else {
            response.sendRedirect(".?error=Invalid username or password");
        }
    }

}
